package com.lry.index;

import com.lry.MappedFile;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.List;

@Slf4j
public class IndexFile {

    private static int hashSlotSize = 4;//每个hash槽的大小
    private static int indexSize = 20;//每个index条目的大小
    private static int invalidIndex = 0;
    private final int hashSlotNum;
    private final int indexNum;
    private final MappedFile mappedFile;
    private final FileChannel fileChannel;
    private final MappedByteBuffer mappedByteBuffer;
    private final IndexHeader indexHeader;

    public IndexFile(final String fileName,final int hashSlotNum,final int indexNum,
                     final long endPhyOffset,final long endTimestamp) throws IOException {
        int totalSize = IndexHeader.INDEX_HEADER_SIZE + (hashSlotNum * hashSlotSize) +
                (indexNum * indexSize);

        this.mappedFile = new MappedFile(fileName,totalSize);
        this.fileChannel = this.mappedFile.getFileChannel();
        this.mappedByteBuffer = this.mappedFile.getMappedByteBuffer();
        this.hashSlotNum = hashSlotNum;
        this.indexNum = indexNum;
        ByteBuffer slice = this.mappedByteBuffer.slice();
        this.indexHeader = new IndexHeader(slice);
        if (endPhyOffset > 0) {
            this.indexHeader.setBeginPhyOffset(endPhyOffset);
            this.indexHeader.setEndPhyOffset(endPhyOffset);
        }

        if (endTimestamp > 0) {
            this.indexHeader.setBeginTimestamp(endTimestamp);
            this.indexHeader.setEndTimestamp(endTimestamp);
        }
    }

    public boolean isTimeMatched(final long begin, final long end) {
        boolean result = begin < this.indexHeader.getBeginTimestamp() && end > this.indexHeader.getEndTimestamp();
        result = result || (begin >= this.indexHeader.getBeginTimestamp() && begin <= this.indexHeader.getEndTimestamp());
        result = result || (end >= this.indexHeader.getBeginTimestamp() && end <= this.indexHeader.getEndTimestamp());
        return result;
    }

    public int indexKeyHashMethod(final String key) {
        int keyHash = key.hashCode();
        int keyHashPositive = Math.abs(keyHash);
        if (keyHashPositive < 0){
            keyHashPositive = 0;
        }
        return keyHashPositive;
    }

    public boolean putKey(final String key,final long phyOffset,final long storeTimestamp){
        if(this.indexHeader.getIndexCount()>=this.indexNum){
            log.warn("Over index file capacity: index count = " + this.indexHeader.getIndexCount()
                    + "; index max num = " + this.indexNum);
            return false;
        }

        int keyHash = indexKeyHashMethod(key);
        int slotPos = keyHash % this.hashSlotNum;//定位到hash槽
        //hash槽在本indexfile的绝对位置
        int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;

        //拿到hash槽那四个字节的值
        int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
        if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) {
            slotValue = invalidIndex;
        }

        //计算消息的存储时间与当前 IndexFile 存放的最小时间差额(单位为秒）。
        long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp();
        timeDiff = timeDiff / 1000;

        if (this.indexHeader.getBeginTimestamp() <= 0) {
            timeDiff = 0;
        } else if (timeDiff > Integer.MAX_VALUE) {
            timeDiff = Integer.MAX_VALUE;
        } else if (timeDiff < 0) {
            timeDiff = 0;
        }

        //计算该 key 存放的条目的起始位置，等于=文件头(IndexFileHeader 40个字节) + (hashSlotNum * 4) + IndexSize(一个条目20个字节) * 当前存放的条目数量。
        int absIndexPos =
                IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
                        + this.indexHeader.getIndexCount() * indexSize;

        //填充 IndexFile 条目，4字节（hashcode） +
        // 8字节（commitlog offset） +
        // 4字节（commitlog存储时间与indexfile第一个条目的时间差，单位秒） +
        // 4字节（同hashcode的上一个的位置，0表示没有上一个）。
        this.mappedByteBuffer.putInt(absIndexPos, keyHash);
        this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset);
        this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff);
        this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue);

        //将当前先添加的条目的位置，存入到 key hashcode 对应的 hash槽，也就是该字段里面存放的是该 hashcode 最新的条目
        this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());

        if (this.indexHeader.getIndexCount() <= 1) {
            this.indexHeader.setBeginPhyOffset(phyOffset);
            this.indexHeader.setBeginTimestamp(storeTimestamp);
        }

        //（同hashcode的上一个的位置，0表示没有上一个），自增hashslot
        if (invalidIndex == slotValue) {
            this.indexHeader.incHashSlotCount();
        }
        this.indexHeader.incIndexCount();
        this.indexHeader.setEndPhyOffset(phyOffset);
        this.indexHeader.setEndTimestamp(storeTimestamp);
        return true;

    }

    public long getEndPhyOffset(){
        return this.indexHeader.getEndPhyOffset();
    }

    public String getFileName() {
        return this.mappedFile.getFileName();
    }

    public long getEndTimestamp() {
        return this.indexHeader.getEndTimestamp();
    }

    public boolean isWriteFull() {
        return this.indexHeader.getIndexCount() >= this.indexNum;
    }

    public void flush() {
        long beginTime = System.currentTimeMillis();
        this.indexHeader.updateByteBuffer();
        this.mappedByteBuffer.force();
        log.info("flush index file elapsed time(ms) " + (System.currentTimeMillis() - beginTime));
    }

    public long getBeginTimestamp() {
        return this.indexHeader.getBeginTimestamp();
    }

    public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum,
                                final long begin, final long end, boolean lock) {
            //计算hash
            int keyHash = indexKeyHashMethod(key);
            int slotPos = keyHash % this.hashSlotNum;
            int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;

            FileLock fileLock = null;
            try {
                if (lock) {
                    // fileLock = this.fileChannel.lock(absSlotPos,
                    // hashSlotSize, true);
                }

                int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
                // if (fileLock != null) {
                // fileLock.release();
                // fileLock = null;
                // }

                if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()
                        || this.indexHeader.getIndexCount() <= 1) {
                } else {
                    for (int nextIndexToRead = slotValue; ; ) {
                        if (phyOffsets.size() >= maxNum) {
                            break;
                        }

                        int absIndexPos =
                                IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
                                        + nextIndexToRead * indexSize;

                        int keyHashRead = this.mappedByteBuffer.getInt(absIndexPos);
                        long phyOffsetRead = this.mappedByteBuffer.getLong(absIndexPos + 4);

                        long timeDiff = (long) this.mappedByteBuffer.getInt(absIndexPos + 4 + 8);
                        int prevIndexRead = this.mappedByteBuffer.getInt(absIndexPos + 4 + 8 + 4);

                        if (timeDiff < 0) {
                            break;
                        }

                        timeDiff *= 1000L;

                        long timeRead = this.indexHeader.getBeginTimestamp() + timeDiff;
                        boolean timeMatched = (timeRead >= begin) && (timeRead <= end);

                        if (keyHash == keyHashRead && timeMatched) {
                            phyOffsets.add(phyOffsetRead);
                        }

                        if (prevIndexRead <= invalidIndex
                                || prevIndexRead > this.indexHeader.getIndexCount()
                                || prevIndexRead == nextIndexToRead || timeRead < begin) {
                            break;
                        }

                        nextIndexToRead = prevIndexRead;
                    }
                }
            } catch (Exception e) {
                log.error("selectPhyOffset exception ", e);
            } finally {
                if (fileLock != null) {
                    try {
                        fileLock.release();
                    } catch (IOException e) {
                        log.error("Failed to release the lock", e);
                    }
                }

            }
    }

    public void load() {
        this.indexHeader.load();
    }
}
